package com.chat.module.email.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chat.module.email.entity.PlayerEmailAssociation;
import com.chat.module.email.entity.SystemEmails;
import com.chat.module.email.mapper.PlayerEmailAssociationMapper;
import com.chat.module.email.vo.SystemEmailVo;
import com.comment.dubbo.service.bag.BagItemService;
import com.comment.exception.ServiceException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;

/**
 * (PlayerEmailAssociation)表服务实现类
 *
 * @author makejava
 * @since 2024-11-05 11:20:23
 */
@Service("playerEmailAssociationService")
public class PlayerEmailAssociationServiceImpl extends ServiceImpl<PlayerEmailAssociationMapper, PlayerEmailAssociation> {
    @Resource
    private PlayerEmailAssociationMapper playerEmailAssociationDao;
    @DubboReference
    private BagItemService bagItemService;
    @Resource
    private SystemEmailsServiceImpl systemEmailsService;

    @SuppressWarnings("unchecked")
    @Transactional
    public boolean updateAttachmentClaimed(Long userId, Long playerEmailId) {
        PlayerEmailAssociation byId = getById(playerEmailId);
        if (!byId.getPlayerUid().equals(userId)) {
            throw new ServiceException("不存在邮件");
        }
        if (byId.getAttachmentClaimed() == 1) {
            throw new ServiceException("邮件已领取");
        }
        Long systemEmailId = byId.getSystemEmailId();
        SystemEmails systemEmails = systemEmailsService.getById(systemEmailId);

        Map<String, Object> attachment = systemEmails.getAttachment();
        if (attachment == null) {
            throw new ServiceException("不存在邮件");
        }

        Map<String, Integer> o = (Map<String, Integer>) attachment.get("prop");
        if (o == null) {
            throw new ServiceException("不存在邮件");
        }
        for (Map.Entry<String, Integer> entry : o.entrySet()) {
            Long propId = Long.valueOf(entry.getKey());
            Long num = Long.valueOf(entry.getValue());
            bagItemService.obtainBagItem(userId, propId, BigDecimal.valueOf(num));
        }
        byId.setAttachmentClaimed(1);
        byId.setReadStatus(1);
        return updateById(byId);
    }
}

